/**
 * Copyright (c) 2011-2016, Eason Pan(pylxyhome@vip.qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jcbase.conf;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.filter.logging.Log4jFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jcbase.core.BaseConstance;
import com.jcbase.core.auth.interceptor.AuthorityInterceptor;
import com.jcbase.core.auth.interceptor.SysLogInterceptor;
import com.jcbase.core.handler.ResourceHandler;
import com.jcbase.core.plugin.process.ProcessPlugin;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.model.SysUser;
import com.jcbase.model._MappingKit;
import com.jcbase.process.WechatMessageProcess;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.ext.plugin.quartz.QuartzPlugin;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.druid.IDruidStatViewAuth;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.render.ViewType;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.cache.RedisAccessTokenCache;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * API引导式配置
 */
public class JcConfig extends JFinalConfig {
	private static final Logger logger = LoggerFactory.getLogger(JcConfig.class);

	/**
	 * 配置常量
	 */
	public void configConstant(Constants me) {
		// 加载少量必要配置，随后可用PropKit.get(...)获取值
		PropKit.use("a_little_config.txt");
		me.setDevMode(PropKit.getBoolean("devMode", false));
		me.setViewType(ViewType.JSP);
	}

	/**
	 * 配置路由
	 */
	public void configRoute(Routes me) {
		me.add(new ApiRoutes());
		me.add(new AdminRoutes());
		me.add(new FrontRoutes());
		me.add(new CommonRoutes());
	}

	public static C3p0Plugin createC3p0Plugin() {
		return new C3p0Plugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password"));
	}

	public static DruidPlugin createDruidPlugin() {
		DruidPlugin dp = new DruidPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password"));
		dp.addFilter(new StatFilter());
		dp.addFilter(new Log4jFilter());
		WallFilter wall = new WallFilter();
		wall.setDbType("mysql");
		dp.addFilter(wall);
		return dp;
	}

	/**
	 * 配置插件
	 */
	public void configPlugin(Plugins me) {
		DruidPlugin druidPlugin = createDruidPlugin();
		me.add(druidPlugin);

		// 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
		arp.setShowSql(PropKit.getBoolean("devMode", false));
		arp.setDevMode(PropKit.getBoolean("devMode", false));
		me.add(arp);
		me.add(new EhCachePlugin());
		// 所有配置在 MappingKit 中搞定
		_MappingKit.mapping(arp);

		String redisHost = PropKit.get("redis.host");
		int redisPort = PropKit.getInt("redis.port");

		//开启redis插件
		RedisPlugin redisPlugin = new RedisPlugin("demo", redisHost, redisPort);
		me.add(redisPlugin);

		JedisPoolConfig poolConfig = configJedisPool();
		JedisPool redisPool = new JedisPool(poolConfig, redisHost, redisPort);
		List<String> queueNames = new ArrayList<String>();
		queueNames.add(BaseConstance.WX_RESPONSE);
		//开启异步消息队列处理插件
		ProcessPlugin processPlugin = new ProcessPlugin(redisPool, queueNames, new WechatMessageProcess());
		me.add(processPlugin);

		//定时任务插件
		QuartzPlugin quartzPlugin = new QuartzPlugin("job.properties");
		me.add(quartzPlugin);
	}

	/**
	 * 配置全局拦截器
	 */
	public void configInterceptor(Interceptors me) {
		me.addGlobalActionInterceptor(new SysLogInterceptor());
		me.addGlobalActionInterceptor(new AuthorityInterceptor());
	}

	/**
	 * 配置处理器
	 */
	public void configHandler(Handlers me) {
		DruidStatViewHandler dvh = new DruidStatViewHandler("/druid", new IDruidStatViewAuth() {
			public boolean isPermitted(HttpServletRequest request) {
				SysUser sysUser = IWebUtils.getCurrentSysUser(request);
				return (sysUser != null && sysUser.getStr("name").equals("admin"));
			}
		});
		me.add(dvh);
		me.add(new ResourceHandler());
	}

	public void afterJFinalStart() {
		logger.info("初始化redis缓存accessToken");
		//1.5 之后支持redis存储access_token、js_ticket，需要先启动RedisPlugin
		ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache(Redis.use("demo")));
	}

	/**
	 * @category 配置jedisPool
	 * @return
	 */
	private JedisPoolConfig configJedisPool() {
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		int maxTotal = PropKit.getInt("redis.max.total");
		int maxIdle = PropKit.getInt("redis.max.idle");
		boolean testOnBorrow = PropKit.getBoolean("test.on.borrow");
		boolean testWhileIdle = PropKit.getBoolean("test.while.idle");
		poolConfig.setMaxTotal(maxTotal);
		poolConfig.setMaxIdle(maxIdle);
		poolConfig.setTestOnBorrow(testOnBorrow);
		poolConfig.setTestWhileIdle(testWhileIdle);
		return poolConfig;
	}

}
